class InstitutionController < ApplicationController
  before_filter :login_required

  layout 'standard'
	
	def new
		@institution = Institution.new
	end

	def list
		sort = case params[:sort]
    when "id" then "id"
    when "name" then "name"
    when "multifunc_institution" then "multifunc_institution"
    when "id_reverse" then "id DESC"
    when "name_reverse" then "name DESC"
    when "multifunc_institution_reverse" then "multifunc_institution DESC"
		end
		
	
		if !params[:institution].nil? && (params[:institution][:multifunc_institution] == "Yes" || params[:institution][:multifunc_institution] == "true")
			params[:institution][:multifunc_institution] = true
		elsif !params[:institution].nil? && (params[:institution][:multifunc_institution] == "No" || params[:institution][:multifunc_institution] == "false")
			params[:institution][:multifunc_institution] = false
		else
			params[:institution] = nil
		end
		
		
		@institutions = Institution.find(:all, :order => sort, :conditions => params[:institution])
		
		if request.xml_http_request?
			render :partial => "institutions_list", :layout => false
		end
	end

	def create
		@institution = Institution.new(params[:institution])
    @institution.save
    if @institution.errors.empty?
      redirect_to :action => 'list'
      flash[:notice] = "Institution created: " + @institution.name
    else
      flash_errors(@institution)
      render :action => 'new'
    end
	end
	
	def edit
		@institution = Institution.find(params[:id])
	end
	
	def update
		@institution = Institution.find(params[:id])
		@institution.update_attributes(params[:institution])

    if @institution.errors.empty?
			flash[:notice] = get_changes_saved_text(@institution)
			redirect_to :action => 'edit', :id => @institution.id
      #redirect_to :back
		else
      flash_errors(@institution)
      render :action => 'edit'
		end
	end

  def delete
    @institution = Institution.find(params[:id])    

    begin
      @institution.destroy
    rescue Exception => e
      flash[:error] = e.message
      redirect_to :back and return
    end
    
    redirect_to :action => 'list'
  end
end
